package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: algorithm
 * @description: 自旋锁
 * @author: 陈恩涛
 * @create: 2022-08-19 16:59
 **/
public class SpinLockDemo {
    public static void main(String[] args) {
        final MySpinLock spinLock = new MySpinLock();

        new Thread(() -> {
            spinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.unlock();
        }, "t1").start();

        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            spinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.unlock();
        }, "t2").start();
    }
}

class MySpinLock{

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        final Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t come in");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    public void unlock() {
        final Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(thread.getName() + "\t task over");
    }
}
